package com.jian.channel;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * @author Jiange
 * @create 2021-09-11-16:28
 */
public class DatagraamChannelTest {
    @Test
    public void send() throws Exception {
        DatagramChannel channel = DatagramChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8888);

        while(true){
            ByteBuffer wrap = ByteBuffer.wrap("李子键".getBytes());
            channel.send(wrap,socketAddress);
            System.out.println("发完了");
            TimeUnit.SECONDS.sleep(2);
        }
    }

    @Test
    public void receive() throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress(8888);
        channel.bind(socketAddress);

        ByteBuffer allocate = ByteBuffer.allocate(1024);
        while(true){
            allocate.clear();
            SocketAddress receive = channel.receive(allocate);

            allocate.flip();
            System.out.println(Charset.forName("utf-8").decode(allocate));
        }
    }
}
